package controller

import (
	"ay-activity/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"time"
)

type DefaultController struct {
}

type DeviceController struct {
}

func (dc DefaultController) Index(c *gin.Context) {
	value := c.Query("token")
	if value == "" {
		c.JSON(500, utils.Fail("参数错误", 500))
		return
	}
	application, err := skinApplication(
		"https://sy-ay-applet.oss-cn-shenzhen.aliyuncs.com/81e767ac1c78e30375db5bca50d359c36e0a701c889581ecaf4cda17c3645d28.jpg",
		value)
	if err != nil {
		c.JSON(500, err)
		return
	}
	c.JSON(200, application)
}

type SkinRequest struct {
	AppID  int    `json:"appid"`
	API    string `json:"api"`
	Params Params `json:"params"`
}

type Params struct {
	ImageURL   string `json:"imageUrl"`
	Dimensions []int  `json:"dimensions"`
}

func skinApplication(images string, token string) (string, error) {
	// 构建请求参数
	dimensions := []int{1}

	request := SkinRequest{
		AppID: 10009,
		API:   "ai-service/ps/v2.0/skin-application",
		Params: Params{
			ImageURL:   images,
			Dimensions: dimensions,
		},
	}

	requestBody, err := json.Marshal(request)
	if err != nil {
		return "", err
	}

	client := &http.Client{
		Timeout: 30 * time.Second,
	}

	req, err := http.NewRequest("POST", "http://skin.wkelian.cn/api/open/v1/", bytes.NewBuffer(requestBody))
	if err != nil {
		return "", err
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("w-token", token)

	startTime := time.Now()
	resp, err := client.Do(req)
	endTime := time.Now()

	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	fmt.Printf("Go HTTP请求耗时: %v\n", endTime.Sub(startTime).Seconds())
	code := resp.StatusCode
	fmt.Println("HTTP状态码:", code)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(body), nil
}
